package io.webchat.minio;

import io.minio.MinioClient;
import io.webchat.wdzl.utils.IpPortUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;

@Component
public class MinIOConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(MinIOConfig.class) ;

    @Autowired
    private ParamConfig paramConfig ;

    private MinioClient minioClient ;




    /**
     * 初始化 MinIO 客户端
     */
    @PostConstruct
    private void init(){
        try {
            minioClient = new MinioClient(paramConfig.getEndpoint(),
                    paramConfig.getAccessKey(),
                    paramConfig.getSecretKey());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("MinIoClient init fail ...");
        }
    }

    /**
     * 创建bucket
     */
    public void createBucket(String bucketName) throws Exception{
        if (!minioClient.bucketExists(bucketName)) {
            minioClient.makeBucket(bucketName);
        }
    }

    /**
     * 上传 <img> 图片
     */
    public String uploadImg (String imgName, String imgPath) throws Exception {
        minioClient.putObject(paramConfig.getBucketNameImage(),imgName,imgPath);
        String path = paramConfig.getEndpoint();
        String ip=IpPortUtil.getIp(path);
        return ip+":"+paramConfig.getImagePort()+"/"+paramConfig.getBucketNameImage()+"/"+imgName ;
    }


    public String uploadImg(MultipartFile file,String bucketName) throws Exception {
        //判断存储桶是否存在  不存在则创建
        createBucket(bucketName);
        String originalFilename = file.getOriginalFilename();
        //新的文件名 = 存储桶文件名_时间戳.后缀名
        String fileName = bucketName + "_" +
                System.currentTimeMillis() +
                originalFilename.substring(originalFilename.lastIndexOf("."));
        minioClient.putObject(bucketName,fileName,file.getInputStream(),file.getContentType());
        String path = paramConfig.getEndpoint();
        String ip=IpPortUtil.getIp(path);
        return ip+":"+paramConfig.getImagePort()+"/"+paramConfig.getBucketNameRent()+"/"+fileName ;
    }



}
